<template>
  <div>
    <div class="condition">
      <div class="condition-text" v-for="(item,index) in conditions" :key="index" @click="onChange(item,index)"
           v-bind:class="{back:index==isActive,change_back:index!=isLine}">
        <span>{{ item }}</span>
      </div>
      <Icon type="ios-refresh" size="25" style="float:right; cursor: pointer; margin-left: 10px;" @click.native="refresh"/>
    </div>
    <div class="pie-main"
         id="box"
         ref="dom"></div>
  </div>
</template>

<script>
import echarts from 'echarts';
import {statApi} from '@/api/stat';
import tdTheme from './theme.json';
import {on, off} from '@/lib/util';

echarts.registerTheme('tdTheme', tdTheme);
export default {
  data() {
    return {
      isActive: false,
      isLine: false,
      data: [],
      dom: null,
      conditions: [
        '近7天', '近30天', '近一年'
      ]
    }
  },
  props: {
    value: Array,
    text: String,
    subtext: String
  },
  watch: {
    data: {
      handler(newVal, oldVal) {
        if (this.dom) {
          if (newVal) {
            this.setOption(newVal);
          } else {
            this.setOption(oldVal);
          }
        } else {
          this.initChart();
        }
      }, deep: true
    }
  },
  mounted() {
    this.getElectricRatios();
  },
  methods: {
    onChange(item, index) {
      this.isActive = index;
      this.isLine = index;
      let timeType = 0;
      switch (index) {
        case 0:
          timeType = 1;
          break;
        case 1:
          timeType = 2;
          break;
        case 2:
          timeType = 3;
          break;
      }
      this.getElectricRatios(timeType)
    },
    async getElectricRatios(timeType) {
      try {
        let params = {
          dateType: timeType
        }
        statApi.countByElectricCoreType(params).then(res => {
          if (res.code === 1) {
            this.data = res.data;
          }
        })
      } catch (e) {
        console.error(e);
      } finally {
      }
    },
    resize() {
      this.dom.resize();
    },
    initChart() {
      this.$nextTick(() => {
        let option = this.getOption();
        this.dom = echarts.init(this.$refs.dom, 'tdTheme');
        this.dom.setOption(option);
        on(window, 'resize', this.resize);
      });
    },
    getOption() {
      let pieData = this.data.data;
      let newData = pieData.length>20?pieData.slice(0,20):pieData
      let disassembleCount = this.data.disassembleCount;
      let option = {
          title: {
            text: this.text,
            subtext: this.subtext,
            x: 'center'
          },
          position: {
            top: 40
          },
          tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)',
            position: function (point, params, dom, rect, size) {
              let leftWidth = size.viewSize[0] / 2 - size.contentSize[0] / 2;
              return {left: leftWidth, bottom: 0};
            },
            backgroundColor: 'transparent',
            textStyle: {
              fontSize: 20,
              color: '#666'
            }
          },
          legend: {
            x: 'right',
            y: 'center',
            left: '55%',
            orient: 'horizontal',
            icon: 'circle',
            textStyle: {
              rich: {
                name: {
                  verticalAlign: 'right',
                  align: 'left',
                  fontSize: 12,
                  color: '#000000'
                },
                value: {
                  align: 'left',
                  fontSize: 12,
                  color: '#999999'
                }
              },
              color: '#54bef9'
            },
            data: newData.map((item) => item.name),
            formatter: function (name) {
              let total = 0;
              let tarValue;
              for (let i = 0; i < pieData.length; i++) {
                total += pieData[i].value;
                if (name === pieData[i].name) {
                  tarValue = pieData[i].value;
                }
              }
              let p = Math.round((tarValue / total) * 100);
              return (
                '{name| ' +
                name +
                '}  ' +
                '{value| ' +
                p +
                '%}'
              );
            }
          },
          series: [
            {
              name: '拆解总数',
              type: 'pie',
              radius: ['45%', '60%'],
              center: ['27%', '52%'],
              avoidLabelOverlap: false,
              label: {
                normal: {
                  show: true,
                  position: 'center',
                  formatter: function () {
                    return "拆解总数\r\n" + disassembleCount;
                  }, textStyle: {
                    fontSize: '24',
                    color: '#666'
                  }
                },
                emphasis: {
                  show: false,
                  textStyle: {
                    fontSize: '24'
                  }
                }
              },
              labelLine: {
                normal: {
                  show: false
                }
              },
              data: pieData
            }
          ]
        };
        return option;
    },
    setOption(value) {
      this.$nextTick(() => {
        let option = this.getOption(value);
        this.dom.setOption(option);
      })
    },
    refresh() {
      this.getElectricRatios();
    }
  }
};
</script>

<style>
.pie-main {
  width: 100%;
  height: 360px;
  background: #fff;
}
</style>
